﻿using log4net;
using Mangox.BLL.Mangox;
using Mangox.Common;
using MGXAPI.BLL;
using MGXAPI.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Http;

namespace MGXAPI.Controllers.API.Mangox
{
    public class MangoxController : ApiController
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";       //获取类名 

        
        private static string createAccountUrl = ConfigurationManager.AppSettings["CreateAccountUrl"];
        private static string getBalanceUrl = ConfigurationManager.AppSettings["GetBalanceUrl"];
        private static string bitPool = ConfigurationManager.AppSettings["BitPool"];
        private static string transferUrl = ConfigurationManager.AppSettings["Transfer"];
        private static string gettxsUrl = ConfigurationManager.AppSettings["Gettxs"];
        private static string pubPackageUrl = ConfigurationManager.AppSettings["PubPackage"];
        private static string getPackageUrl = ConfigurationManager.AppSettings["GetPackage"];

        //属性写法
        //public static string TransferUrl { get => transferUrl; set => transferUrl = value; }


        /// <summary>
        /// http://localhost:13772/api/Mangox/CreateUser
        /// 创建Hash账户,外部未开放
        /// </summary>
        /// <returns></returns>
        public static string CreateMgxUser()
        {
            return null;
        }

        /// <summary>
        /// Api 查询余额
        /// http://localhost:13772/api/Mangox/GetBalance
        /// param:{"Token":"DDgp61o7H0njRWVNNol4rFpsLfWBrr6/RatRLPpt1/6qTsGCMOkvda7AJCUHPD0VOf4PErgoaOVwdIzTj091DzkJ5cN2kSZm1blnzwHlELcEPB1uoKMN2dZAKuOkSfmY","Source":1,"Param":{"userHash":"b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f"}}
        /// </summary>
        /// <param name="hash"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetBalance(RequestModel p)
        {
            ResultModel result = new ResultModel();
            result.Code = -1;
            string UserHash = null;

            try
            {
                log.Info($"查询余额Param-：{JsonConvert.SerializeObject(p)}");
                UserHash = p.Param.userHash;
                
                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);

                #endregion

                if (string.IsNullOrWhiteSpace(UserHash))
                {
                    result.Msg = "User为空";
                    return result;
                }

                var ret = new MgxBLL().GetBalanceIn(UserHash);
                if (!string.IsNullOrEmpty(ret))
                {
                    result.Code = 0;
                    result.Data = double.Parse(Convert.ToDouble(ret).ToString("0.00"));
                }
                else
                {
                    result.Data = 0;
                    result.Msg = "服务器开小差了，查询异常";
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"查询余额失败：GetBalance，Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 转账API
        /// http://localhost:13772/api/Mangox/Transfer
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel Transfer(RequestModel p)
        {
            log.Info($"转账Param-：{JsonConvert.SerializeObject(p)}");

            //var json = "ret=0&res_info=3e948681603e4b2f4eb45af5bfc6db17444017b39267c9c845449dcc44f5328f";
            //{"ret":0,"res_info":"ok","hash":"74123723f89c013fb48b7bb1797d6bd6ce3bb648565b5d54f5e59508e2a10a12","amount":10.0}
            ResultModel result = new ResultModel();
            result.Code = -1;
            string json = null;
            string url = null;

            //p.Param.userHash = "0c8256cb55462ec97b90584343e9acf6201550e4540feb0ab3fd2c598b9795a2";
            //p.Param.toUserHash = "b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f";
            //p.Param.toAmount = 1;

            try
            {
                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);

                #endregion

                //if (string.IsNullOrEmpty(p.Param.toUserHash.ToString())
                //    || Convert.ToString(p.Param.toUserHash).Trim().Length != 64)
                //{
                //    result.Data = null;
                //    result.Msg = "收金币人错误";
                //    return result;
                //}

                if (string.IsNullOrEmpty(p.Param.toUserHash.ToString())
                    || Convert.ToString(p.Param.toUserHash).Trim().Length != 64)
                {
                    result.Data = null;
                    result.Msg = "收金币人错误";
                    return result;
                }

                if (!OtherHelper.IsNumber(p.Param.toAmount.ToString()))
                {
                    result.Data = null;
                    result.Msg = "请填写数字";
                    return result;
                }

                if (p.Param.toAmount.ToString().Contains("."))
                {
                    result.Data = null;
                    result.Msg = "请选择整数";
                    return result;
                }
                
                if (Convert.ToDecimal(p.Param.toAmount) <= 0)
                {
                    result.Data = null;
                    result.Msg = "数额错误";
                    return result;
                }

                if ((Convert.ToDecimal(p.Param.amount) - Convert.ToDecimal(p.Param.toAmount) < 0))
                {
                    result.Data = null;
                    result.Msg = "金币不足";
                    return result;
                }

                JsonRequest request = new JsonRequest();
                url = string.Format(transferUrl, bitPool, p.Param.userHash, p.Param.toUserHash, p.Param.toAmount);
                json = request.Get(url);
                log.Info($"转账url-：{url}");
                log.Info($"转账result-：{json}");

                //反转将json返回回dynamic对象
                var model = JsonConvert.DeserializeObject<dynamic>(json);
                if (model != null && model.ret == 0)
                {
                    result.Code = 0;
                    result.Data = p.Param.amount - model.amount;
                }
                else
                {
                    result.Msg = "服务器开小差了，赠送异常";
                    //格式化新语法
                    log.Info(className + $"赠送失败Transfer url-{url}，result-{json}");
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"赠送失败Transfer url-{url}，result-{json}，Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 拉取交易流水API
        /// http://localhost:13772/api/Mangox/Gettxs
        /// param:{"Token":"DDgp61o7H0njRWVNNol4rFpsLfWBrr6/RatRLPpt1/6qTsGCMOkvda7AJCUHPD0VOf4PErgoaOVwdIzTj091DzkJ5cN2kSZm1blnzwHlELcEPB1uoKMN2dZAKuOkSfmY","Source":1,"Param":{"userHash":"5b1e5387031f1de30457c874cbaa797da29ad4bdd061d7f69996862591a14ef1","type":"1"}}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel Gettxs(RequestModel p)
        {
            //[{\"i\":\"c2c4adc1d0acf6\",\"ot\":\"cc6f23392600cda\",\"amount\":50.0,\"nonce\":\"05E75\",\"time\":\"2019-05-15 00:10:12.0\",\"type\":\"TXIN\"},{\"i\":\"c2c4adc1d0acf6\",\"ot\":\"cc6f23392600cda\",\"amount\":50.0,\"nonce\":\"05E75\",\"time\":\"2019-06-16 02:10:12.0\",\"type\":\"TXIN\"}]
            //var json = "{"ret":0,"res_info":"ok","units":[]}";
            //{"ret":0,"res_info":"ok","units":[{"in":"0c8256cb55462ec97b90584343e9acf6201550e4540feb0ab3fd2c598b9795a2","out":"b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f","amount":5.0,"nonce":"EFA135B33CFE49AB84C9D3407C45A699","time":"2019-05-24 21:20:05.0","type":"TXOUT"},{"in":"b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f","out":"0c8256cb55462ec97b90584343e9acf6201550e4540feb0ab3fd2c598b9795a2","amount":10.0,"nonce":"E66C536B2889461EBFB928BC3781F8D7","time":"2019-05-24 20:51:03.0","type":"TXIN"},{"in":"0f7859b6fcc8c12a95c38f942fb5497ac6fa3b3dc16ce840c3e4e353cf2a2113","out":"b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f","amount":3000.0,"nonce":"DA0975D5B2854DFAA4A37241F06E1D5B","time":"2019-05-19 22:35:40.0","type":"TXOUT"}]}

            //有中文的返回，中文是编码
            //url = "http://106.75.168.107:8001/gettxs?hash=5b1e5387031f1de30457c874cbaa797da29ad4bdd061d7f69996862591a14ef1&type=1";
            //{"ret":0,"res_info":"ok","units":[{"in":"5b1e5387031f1de30457c874cbaa797da29ad4bdd061d7f69996862591a14ef1","out":"%E8%8B%8F%E6%98%BE%E5%8D%8E","amount":36.0,"nonce":"C192629EBD1C446EA67458BD816E4D1B","time":"2019-07-02 03:44:06.0","type":"TXIN"},{"in":"5b1e5387031f1de30457c874cbaa797da29ad4bdd061d7f69996862591a14ef1","out":"%E8%8B%8F%E6%98%BE%E5%8D%8E","amount":40.44,"nonce":"C2551649CA9A4F2BBF0470980A01B2DA","time":"2019-07-02 03:43:52.0","type":"TXIN"}]}

            ResultModel result = new ResultModel();
            result.Code = -1;
            string json = null;
            string url = null;
            string type = p.Param.type; //type=1表示流水可以查询中文名称

            log.Info($"查交易流水Param-：{JsonConvert.SerializeObject(p)}");

            try
            {
                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);

                #endregion

                JsonRequest request = new JsonRequest();
                //userHash可能也是合约hash，查询红包人员列表
                url = string.Format(gettxsUrl, bitPool, p.Param.userHash);
                if (!string.IsNullOrWhiteSpace(type) && type == "1")
                {
                    url += "&type=" + type;
                }

                //--test
                //url = "http://106.75.168.107:8001/gettxs?hash=5b1e5387031f1de30457c874cbaa797da29ad4bdd061d7f69996862591a14ef1&type=1";
                //url = "http://106.75.168.107:8001/gettxs?hash=aa926d016920dc39caf6b033bd1e3a2c52ed22800012028a77f1c6242beefc69&type=1";

                json = request.Get(url);

                //if (MvcApplication.isDebug)
                //{
                //    json = "{\"ret\":0,\"res_info\":\"ok\",\"units\":[{\"in\":\"9652bcbc7b067fed4b6d16b9e36e0dbb69a1475ccb051a8c8427f4efe6ac466a\",\"out\":\"%E6%99%B4%E5%A4%A9\",\"amount\":0.83,\"nonce\":\"7EE08F4479BF43D7AE6DBD511D709C35\",\"time\":\"2019-07-03 10:55:06.0\",\"type\":\"TXIN\"},{\"in\":\"%E6%99%B4%E5%A4%A9\",\"out\":\"9652bcbc7b067fed4b6d16b9e36e0dbb69a1475ccb051a8c8427f4efe6ac466a\",\"amount\":10.0,\"nonce\":\"ADE859C4035A4AC6803105CADE2C0B19\",\"time\":\"2019-07-03 10:54:56.0\",\"type\":\"TXOUT\"}],\"sender\":\"894bb72223838c6207f1d4141a57caa70003b0c5ebb8315c23167cf094f3b092\",\"total\":\"1000\"}";
                //}

                log.Info($"查交易流水url-：{url}");
                log.Info($"查交易流水result-：{json}");

                //反转将json返回回dynamic对象，json字符串转对象
                var model = JsonConvert.DeserializeObject<dynamic>(json);
                var list = model.units;
                var senderName = ""; //发红包人
                int delIndex = 0;
                if (model != null && model.ret == 0)
                {
                    if (list != null && list.Count > 0)
                    {
                        string userName = null;
                        int i = 0;

                        //查出发红包人
                        if (type == "1")
                        {
                            string shash = model.sender.ToString();
                            senderName = new MgxUserBLL().GetUserByMgxHashID(shash).UserName;
                        }

                        foreach (var item in list)
                        {
                            try
                            {
                                userName = item["out"];
                                if (type == "1")
                                {
                                    //解码
                                    item.userName = HttpUtility.UrlDecode(userName, Encoding.UTF8);
                                    if (item.type == "TXIN")
                                    {
                                        item.amount = "+" + Convert.ToDouble(item.amount).ToString("0.00");
                                    }
                                    else if (item.type == "TXOUT")
                                    {
                                        item.amount = "-" + Convert.ToDouble(item.amount).ToString("0.00");
                                    }
                                    item.time = Convert.ToDateTime(item.time).ToString("HH:mm");

                                    //清空不需要字段
                                    item["in"] = "";
                                    item["out"] = "";
                                    item["nonce"] = "";

                                    if (item.type == "TXOUT")
                                    {
                                        delIndex = i;
                                        item["amount"] = "";
                                        item["time"] = "";
                                        item["type"] = "";
                                        item.userName = "";
                                        continue;
                                    }
                                }
                                else
                                {
                                    if (item.type == "TXIN")
                                    {
                                        item.type = "送出";
                                        item.amount = "-" + Convert.ToDouble(item.amount).ToString("0.00");
                                        //item.time = "";
                                    }
                                    else if (item.type == "TXOUT")
                                    {
                                        item.type = "获得";
                                        item.amount = "+" + Convert.ToDouble(item.amount).ToString("0.00");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                log.Error(className + $"查询流水循环 url-{url}，result-{JsonCommon.ToJson<dynamic>(item)}，Fail-{ex.ToString()}");
                            }
                            i++;
                        }
                    }
                    result.Code = 0;
                    if (type == "1" && delIndex > 0)
                    {
                        list.Remove(list[delIndex]);
                    }
                    result.Data = new { list =  list, sname = senderName};
                }
                else
                {
                    result.Msg = "服务器开小差了，查询记录异常";
                    log.Info(className + $"查询流水 url-{url}，result-{json}");
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"Gettxs url-{url}，result-{json}，Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 发红包，生成红包API
        /// http://localhost:13772/api/Mangox/PubPackage
        /// param:{"Token":"DDgp61o7H0njRWVNNol4rFpsLfWBrr6/RatRLPpt1/6qTsGCMOkvda7AJCUHPD0VOf4PErgoaOVwdIzTj091DzkJ5cN2kSZm1blnzwHlELcEPB1uoKMN2dZAKuOkSfmY","Source":1,"Total":100,"Number":5,"Sender":""}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel PubPackage(PubPackageModelReq p)
        {
            //http://矿池/pubpackage?total=20&number=5&sender=账户
            //var json = "ret=0&res_info=ok&pkghash=红包合约地址&dephash=红包托管账户";
            //返回：ret=0&res_info=ok&pkghash=eeb818ea5430b63f506e223943e3731d64061dc92c8c683a110f85646764f3b1&dephash=6525e8b3aeb275ccb24088787ecc3fc591b299129a2a82e74b1915e60462cb72
            //      ret=0&res_info=ok&pkghash=1e964ec16b7b5929a350258c4a30d6884995827a196f3c44e90ac5a30c30cc45&dephash=8553f1576c88ad5f60a52044f716adc81cee35c130c45dc023c67e3d8ebbb37d
            ResultModel result = new ResultModel();
            result.Code = -1;
            string ret = null;
            string url = null;

            log.Info($"塞金币Param-：{JsonConvert.SerializeObject(p)}");

            try
            {
                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);

                #endregion

                //验证参数...

                p.Total = p.Total * 100;
                JsonRequest request = new JsonRequest();
                url = string.Format(pubPackageUrl, bitPool, p.Total, p.Number, p.Sender);
                ret = request.Get(url);

                log.Info($"塞金币url-：{url}");
                log.Info($"塞金币result-：{ret}");

                //解析为键值对
                var kv = Comm.ExtractQueryParams("html?" + ret);
                if (kv != null && kv.Count >= 0 && kv["ret"].ToString() == "0")
                {
                    result.Code = 0;
                    result.Data = new
                    {
                        res_info = kv["res_info"].ToString(),
                        pkgm = kv["pkghash"].ToString(),
                        depk = kv["dephash"].ToString(),
                    };
                }
                else
                {
                    result.Msg = "服务器开小差了，塞金币异常";
                    log.Info(className + $"塞金币失败 url-{url}，result-{ret}");
                }
            }
            catch (Exception ex)
            {
                log.Error(className + $"塞金币失败：PubPackage url-{url}，result-{ret}，Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 抢红包API
        /// http://localhost:13772/api/Mangox/GetPackage
        /// {"Token":"DDgp61o7H0njRWVNNol4rFpsLfWBrr6/RatRLPpt1/6qTsGCMOkvda7AJCUHPD0VOf4PErgoaOVwdIzTj091DzkJ5cN2kSZm1blnzwHlELcEPB1uoKMN2dZAKuOkSfmY","Source":1,"PkgHash":"eeb818ea5430b63f506e223943e3731d64061dc92c8c683a110f85646764f3b1","GetterUserHash":"b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f","UserName":"xiaoming"}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultModel GetPackage(GetPackageModelReq p)
        {
            //var json = "ret=0&res_info=ok&amount=4";
            //返回：ret=0&res_info=ok&amount=1&getter=b7ac67fb2d7377fad96c56197f27679067b14d36549f73839575b9d4cd35ad4f
            //返回2 已经抢过了：ret=-1&res_info=you had get the package yeah
            //返回3 已抢光：ret=0&res_info=package done
            //返回4 没有合约/合约延迟：ret=1108&res_info=the address isn't exist
            ResultModel result = new ResultModel();
            result.Code = -1;
            string ret = null;
            string url = null;

            log.Info($"抢金币Param-：{JsonConvert.SerializeObject(p)}");

            try
            {
                #region 验证Token

                var token = MgxCommBLL.DecryptToken(p.Token);
                if (token == null || !token.IsToken)
                {
                    result.Msg = "Token无效或过期";
                    return result;
                }
                result.TokenUpdate = MgxCommBLL.CreateToken(token.UserID.ToString(), token.MgxHashID);

                #endregion

                JsonRequest request = new JsonRequest();


                url = string.Format(getPackageUrl, bitPool, p.Pkgm, p.MgxHashID, HttpUtility.UrlEncode(p.UserName, Encoding.UTF8));
              
                ret = request.Get(url);
                log.Info($"抢金币url-{url}");
                log.Info($"抢金币result-：{ret}");

                //解析为键值对
                var kv = Comm.ExtractQueryParams("html?" + ret);
                if (kv != null && kv.Count >= 0 && kv["ret"].ToString() == "0" && kv["res_info"].ToString() == "ok")
                {
                    result.Code = 0;
                    result.Data = new
                    {
                        //res_info = kv["res_info"].ToString(),
                        amount = Convert.ToDouble(kv["amount"].ToString()) / 100,
                        //getter = kv["getter"].ToString(),
                    };
                }
                else if(kv != null && kv.Count >= 0 && kv["ret"].ToString() == "-1" && kv["res_info"].ToString() == "you had get the package yeah")
                {
                    result.Code = 1;
                    result.Msg = "已经抢过了";
                }
                else if (kv != null && kv.Count >= 0 && kv["res_info"].ToString() == "package get done")
                {
                    result.Code = 3;
                    result.Msg = "已抢光";
                }
                else if (kv != null && kv.Count >= 0 && kv["res_info"].ToString() == "the address isn't exist")
                {
                    result.Code = 4;
                    //result.Msg = "合约不存在或延迟，请稍后再试";
                    result.Msg = "服务器正在生成，请稍后几秒再试";
                }
                else
                {
                    result.Msg = "服务器开小差了";
                    log.Info(className + $"抢金币失败：GetPackage url-{url}，result-{ret}");
                }
            }
            catch (Exception ex)
            {
                result.Msg = "服务器开小差了，请稍后再试";
                log.Error(className + $"抢金币失败：GetPackage url-【{url}】，result-【{ret}】，Fail-{ex.ToString()}");
                log.Error(className + $"抢金币失败：GetPackage url-【{url}】，result-【{ret}】，Fail-{ex.ToString()}");
            }
            return result;
        }

        /// <summary>
        /// test
        /// http://localhost:13772/api/Mangox/test
        /// 保留，job调用
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Test()
        {
            return "test";
        }

    }
}
